package models

import (
	"fmt"
	"log"
	"math/rand"
)

// 对应 zb_tag 表
type ZBTag struct {
	Id            int64
	Parent        int64
	Name          string
	Ident         string
	Sorder        int
	Weight        int
	Relation_tags string
	Status        int
	Type          int
}

func (t ZBTag) TableName() string {
	return "zb_tags"
}

func (tt *ZBTag) getTagByIdent(ident string) int64 {
	t := new(ZBTag)
	engine.Where("ident = ?", ident).Get(t)
	return t.Id
}

// InsertTag 插入标签
func (tt ZBTag) InsertTag(tagname string, p int64, types int, repeat bool) int64 {
	tagIdent := GetIdent(tagname)
	oldID := tt.getTagByIdent(tagIdent)
	if oldID > 0 {
		if !repeat {
			return oldID
		}
		tagIdent = GetIdent(tagname + fmt.Sprintf("xxx%d", rand.Intn(1000)))
	}
	if p < 0 {
		p = 0
	}
	t := &ZBTag{Name: tagname, Ident: tagIdent, Parent: p, Sorder: 1, Weight: 1, Status: 1, Type: types}
	_, err := engine.Insert(t)
	log.Printf("inserting tag  {id: %d;\tname: %s;\tparent: %d\n", t.Id, t.Name, t.Parent)
	if err != nil {
		log.Println("insert tag error ", err)
	}
	return t.Id
}
